#include "Renderer.h"

void setFrustumMat(float l, float r, float b, float t, float n, float f, Eigen::Matrix4f &matrixProjection)
{

	matrixProjection.Identity();
	matrixProjection(0,0)  =  2 * n / (r - l);
	matrixProjection(0,3)  =  (r + l) / (r - l);
	matrixProjection(1,1)  =  2 * n / (t - b);
	matrixProjection(1,2)  =  (t + b) / (t - b);
	matrixProjection(2,2) = -(f + n) / (f - n);
	matrixProjection(2,3) = -(2 * f * n) / (f - n);
	matrixProjection(3,2) = -1;
	matrixProjection(3,3) =  0;
}

HandModelRenderer::HandModelRenderer()
{
	// Create Constant Values
	/*x+- 12.8 ; y+-7.48*/
	screen_width = 640;
	screen_height = 480;
	pixel_per_mm = PIXEL_PER_MM;  // Ti le giua so pixel voi kich thuoc thuc cua tay
	mm_per_Pixel = 0.700035f;

	frushtum_focal = KINECT_DEPTH_NOMINAL_FOCAL_LENGTH_IN_PIXELS;//(pixels) ~ 400mm : 
	frushtum_far = 1999.9f;//(pixels) ~ 1400mm

	m_RX=0;m_RY=0;m_RZ=0;
	depth=1000;posX=0;posY=0;
}

HandModelRenderer::~HandModelRenderer()
{

}

void HandModelRenderer::initializeGLContext()
{
	if (!glfwInit())
		exit(EXIT_FAILURE);
	window = glfwCreateWindow((int)screen_width,(int)screen_height, "Hand Example", NULL, NULL);
	
	if (!SHOW_DEBUG)glfwHideWindow(window);
	
	if (!window)
	{
		glfwTerminate();
		exit(EXIT_FAILURE);
	}
	glfwMakeContextCurrent(window);
	setFrustumMat(-screen_width/2,screen_width/2,-screen_height/2,
		screen_height/2,frushtum_focal,frushtum_far,
		matrixProjection);
}

cv::Mat HandModelRenderer::renderHandModel()
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glLoadMatrixf(matrixProjection.transpose().data()); 
	glEnable( GL_DEPTH_TEST ); 
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	rHand.drawHand();// draw hand data

	glfwSwapBuffers(window);
	glfwPollEvents();

	return rHand.get_gl_depth((int)screen_width,(int)screen_height);
}

void HandModelRenderer::terminateGLContext()
{
	glfwDestroyWindow(window);
	glfwTerminate();
	exit(EXIT_SUCCESS);
}